package com.xavier.dong.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author XavierDong
 **/
public class GroupChatServer {

    // 监听端口
    private int port;

    public GroupChatServer(int port) {
        this.port = port;
    }


    // 编写 run 方法，处理客户端请求
    public void run() {

        // 首先 创建 2个 线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();  // 32个 NioEventLoop

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            // 获取 到 pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            // 向 pipeline 加入 解码器
                            pipeline.addLast("decoder", new StringDecoder());

                            // 向 pipeline 加入 编码器
                            pipeline.addLast("encode", new StringEncoder());

                            // 加入 自己的 业务处理 Handler
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });

            System.out.println("Netty 服务器启动");
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

            // 监听 关闭 事件
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }
    }


    public static void main(String[] args) {
        new GroupChatServer(7000).run();

    }
}
